package com.sfh.base.mvp;


import com.sfh.base.RetrofitManager;

import java.lang.ref.SoftReference;

import rx.Subscription;

/**
 * 功能描述:基础业务控制实现
 *
 * @date 2016/11/15
 */

public class AbstractPstBase<T extends IView> implements IPresenter<T> {

    // 视图回调
    private SoftReference<T> viewHolder;

    // 生命周期状态值 默认 ON_CREATE
    private int lifecycleEvent = Event.ON_CREATE;

    private RetrofitManager retrofit = new RetrofitManager ();

    @Override
    public void attachView(T iView) {

        this.viewHolder = new SoftReference<> (iView);
        this.lifecycleEvent = Event.ON_CREATE;
    }

    @Override
    public void detachView() {

        if (this.viewHolder != null) {
            this.viewHolder.clear ();

        }
        this.viewHolder = null;
    }

    @Override
    public T getView() {

        T view = null == this.viewHolder ? null : this.viewHolder.get ();
        return view;
    }

    @Override
    public boolean isAttach() {

        boolean isBind = this.viewHolder == null ? false : this.viewHolder.get () == null ? false : true;
        boolean isLife = !isNOLife ();
        return isBind && isLife;
    }

    @Override
    public boolean isNoAttach() {

        return !isAttach ();
    }

    private boolean isNOLife() {

        return this.lifecycleEvent == Event.ON_DESTROY || Event.ON_FINISH == this.lifecycleEvent;
    }


    @Override
    public void onLifecycleEvent(IView listener, int event) {

        this.lifecycleEvent = event;
        switch (event) {
            case Event.ON_CREATE: {
                this.attachView ((T) listener);
                break;
            }
            case Event.ON_FINISH: {
                this.unSubscribeAll ();
                this.detachView ();
                break;
            }
            case Event.ON_DESTROY:
                break;
        }
    }

    /***
     * 添加业务层监听
     */
    public int putSubscribe(Subscription subscription) {

        int taskId = subscription.hashCode ();
        retrofit.putSubscribe (taskId, subscription);
        return taskId;
    }

    /***
     * 取消业务层监听
     */
    public void unSubscribeAll() {

        retrofit.unSubscribeAll ();
    }
}
